/* eslint-disable vue/html-indent */
import { getRootWindow } from '@src/util/dom'

/** 
 * @description 获取用户id
*/
function getUserId() {  
  try {
    const RootWindow  = getRootWindow(window)
    const RootWindowInitData = JSON.parse(RootWindow._init)
    
    // 添加企业的特殊标识
    const companyId = RootWindowInitData?.user?.tenantId || null;
    
    return `${companyId}_${RootWindowInitData?.user?.userId}`
  } catch (error) {
    console.warn('storage.js find userId is Null')
    return null
  }
}

export function storageGet(key, defaultValue) {
  try {
    key = `${key}_${getUserId()}`;
    return localStorage.getItem(key) || defaultValue;
  } catch (error) {
    console.error(`storageGet -> error ${error}`)
    return defaultValue
  }
}

export function storageSet(key, value) {
  if(!key) return (
    console.warn('Caused: can not set storage, because not key')
  )
  
  try {
    key = `${key}_${getUserId()}`;
    localStorage.setItem(key, value);
  } catch (error) {
    console.error('stroageSet -> error', error)
  }
}

export function storageRemove(key, value) {
  if(!key) return (
    console.warn('Caused: can not set storage, because not key')
  )
  
  try {
    key  = `${key}_${getUserId()}`;
    localStorage.removeItem(key, value);
  } catch (error) {
    console.error('stroageSet -> error', error)
  }
}


export function sessionStorageGet(key, defaultValue) {
  try {
    key  = `${getUserId()}_${key}`;
    return sessionStorage.getItem(key) || defaultValue;
  } catch (error) {
    console.error(`storageGet -> error ${error}`)
    return defaultValue
  }
}

export function sessionStorageSet(key, value) {
  if(!key) return (
    console.warn('Caused: can not set storage, because not key')
  )
  
  try {
    key  = `${getUserId()}_${key}`;
    sessionStorage.setItem(key, value);
  } catch (error) {
    console.error('stroageSet -> error', error)
  }
}

export function sessionStorageRemove(key, value) {
  if(!key) return (
    console.warn('Caused: can not set storage, because not key')
  )
  
  try {
    key  = `${getUserId()}_${key}`;
    sessionStorage.removeItem(key, value);
  } catch (error) {
    console.error('stroageSet -> error', error)
  }
}

export function storageSetDepth(key, value, rootKey = '') {
  if(rootKey && key) {
    
    let rootValue = storageGet(rootKey, '{}')
    
    rootValue = JSON.parse(rootValue)
    rootValue.key = value
    
    storageSet(rootKey, rootValue)
  } else {
    storageSet(key, value)
  }
}